/**
 * #### 将数字转换为中文小写
 * @see https://www.bilibili.com/video/BV16g4y1174z?spm_id_from=333.788.videopod.sections&vd_source=9efadbd9bd76b9c14f9589f260a0c1ac
 * @author Duyi
 * @date 2022-11-30
 * @category Number
 * @param num 数字
 * @returns 中文小写
 * @example
 * ```ts
 * toChineseNumber(1234567890) // 一亿二千三百四十五万六千七百八十
 * ```
 */
export function toChineseNumber(num: number) {
  const cnNums = ["零", "一", "二", "三", "四", "五", "六", "七", "八", "九"];
  const cnIntRadice = ["", "十", "百", "千"];
  const cnIntUnits = ["", "万", "亿", "兆"];

  const strs = num
    .toString()
    .replace(/(?=(\d{4})+$)/g, ",")
    .split(",")
    .filter(Boolean);

  function _transform(numStr: string) {
    let res = "";
    for (let i = 0; i < numStr.length; i++) {
      const digit = +numStr[i];
      const c = cnNums[digit];
      const u = cnIntRadice[numStr.length - i - 1];
      if (digit === 0) {
        if (res[res.length - 1] !== "零") {
          res += c;
        }
      } else {
        res += c + u;
      }
    }
    if (res[res.length - 1] === cnNums[0]) {
      res = res.slice(0, -1);
    }
    return res;
  }

  let result = "";
  for (let i = 0; i < strs.length; i++) {
    const part = strs[i];
    const c = _transform(part);
    const u = c ? cnIntUnits[strs.length - i - 1] : "";
    result += c + u;
  }
  return result;
}

/**
 * #### 将数字转换为中文大写
 * @see https://www.bilibili.com/video/BV16g4y1174z?spm_id_from=333.788.videopod.sections&vd_source=9efadbd9bd76b9c14f9589f260a0c1ac
 * @author Duyi
 * @date 2022-08-26
 * @category Number
 * @param num 数字
 * @returns 中文大写
 * @example
 * ```ts
 * toChineseBigNumber(1234567890) // 壹拾贰亿叁仟肆佰伍拾陆万柒仟捌佰玖拾
 * ```
 */
export function toChineseBigNumber(num: number) {
  const str = toChineseNumber(num);
  const map = {
    零: "零",
    一: "壹",
    二: "贰",
    三: "叁",
    四: "肆",
    五: "伍",
    六: "陆",
    七: "柒",
    八: "捌",
    九: "玖",
    十: "拾",
    百: "佰",
    千: "仟",
    万: "万",
    亿: "亿",
  };
  return str
    .split("")
    .map((item) => map[item])
    .join("");
}
